package com.example.test.converter;

import com.example.test.utils.SpringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.persistence.AttributeConverter;

/**
 * Json转换器
 * @param <T>
 */
public abstract class JsonConverter<T> implements AttributeConverter<T, String> {
    private static ObjectMapper objectMapper;
    protected ObjectMapper getObjectMapper(){
        if(objectMapper == null){
            objectMapper = SpringUtils.getBean(ObjectMapper.class);
        }
        return objectMapper;
    }

    @Override
    public String convertToDatabaseColumn(T t) {
        try {
            return getObjectMapper().writeValueAsString(t);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
